package com.example.person_web.core.component;

import com.example.person_web.core.dao.LoginRegisterDAO;
import com.example.person_web.core.entity.UserInfoDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private LoginRegisterDAO loginRegisterDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfoDO userInfoDO = loginRegisterDAO.queryUserInfoByAccount(username);

        // 如果用户不存在，抛出异常
        if (userInfoDO == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 1. 配置用户权限（关键修复）
        // 方式一：添加默认权限（推荐，至少给一个基础权限）
        List<GrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_USER") // 普通用户角色
        );


        // 2. 构建UserDetails对象并返回
        return org.springframework.security.core.userdetails.User
                .withUsername(userInfoDO.getAccount())
                .password(userInfoDO.getPassword())
                .authorities(authorities) // 设置权限集合（解决null问题）
                .accountExpired(false) // 账号未过期
                .accountLocked(false)  // 账号未锁定
                .credentialsExpired(false) // 密码未过期
                .disabled(false)// 账号启用
                .build();
    }
}
